﻿using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Configuration;
using Ultimus.OC;

namespace H2.NET.Common
{
    /// <summary>
    /// clsCommon 的摘要说明
    /// </summary>
    public class clsCommon
    {
        #region 公共常量
        public string comm_username = "";
        public string comm_short_username = "";
        public string comm_userfullname = "";
        public string comm_userdepartment = "";
        public string comm_domain = "";
        public string comm_job = "";
        public string comm_mail = "";
        public string comm_language = "zh-cn";
        public bool comm_is_administrator = false;

        public TaskDB clsDB = new TaskDB();
        public Report clsRpt = new Report();
        public Data clsData = new Data();
        #endregion

        #region 多语言字典
        string[,] strTextType = new string[,]{    {"frm_logon_title","Logon","登陆"}
                                                 ,{"frm_logon_help_title","Help","帮助"}
                                                 ,{"frm_logon_help_appno","Applicaton No","流程编号"}
                                                 ,{"frm_logon_help_time","Time","保存时间"}
                                                 ,{"frm_logon_help_url","help/help.zip","help/help.zip"}
                                                 ,{"frm_logon_txtUserName","User Name:","用户名:"}
                                                 ,{"frm_logon_txtPassword","Password:","密码:"}
                                                 ,{"frm_logon_drpDomain","Domain:","域:"}
                                                 ,{"frm_logon_btnLogin","Login","登陆"}
                                                 ,{"frm_logon_pwd_err","Username or password error!","用户名或密码错误!"}
                                                 ,{"frm_logon_pwd_err2","Please contact DMO to create the user account.","请联系DMO建立帐户。"}

                                                 ,{"frm_index_title","Ultimus BPM Software + Business Process Management + Workflow Automation","Ultimus BPM 软件 + 业务流程管理 + 工作流自动化"}
                                                 ,{"frm_index_logoff","Logoff","退出"}
                                                 ,{"frm_index_help_title","Help","帮助"}
                                                 ,{"frm_index_help_url","http://one.akzonobel.intra/bu/113_11/functions/IM/dmo/Shared%20Documents/Forms/AllItems.aspx?RootFolder=%2fbu%2f113%5f11%2ffunctions%2fIM%2fdmo%2fShared%20Documents%2fMDC%20system&FolderCTID=&View=%7b03D95DF6%2d62AF%2d4FEC%2d81D9%2dFBDC5F14242F%7d","http://one.akzonobel.intra/bu/113_11/functions/IM/dmo/Shared%20Documents/Forms/AllItems.aspx?RootFolder=%2fbu%2f113%5f11%2ffunctions%2fIM%2fdmo%2fShared%20Documents%2fMDC%20system&FolderCTID=&View=%7b03D95DF6%2d62AF%2d4FEC%2d81D9%2dFBDC5F14242F%7d"}
                                                 ,{"frm_index_first_show_url","workflow/initiate.aspx","workflow/initiate.aspx"}
                                                 ,{"frm_index_hello","Hello, ","您好，"}

                                                 ,{"frm_initiate_title","New Requisition","发起箱"}
                                                 ,{"frm_initiate_btnSearch","Search"," 查 找 "}
                                                 ,{"frm_initiate_btnDelete","Delete"," 删 除 "}
                                                 ,{"frm_initiate_txtProcess","Process Name:","流程名:"}
                                                 ,{"frm_initiate_txtStep","Step Name:","步骤名称:"}
                                                 ,{"frm_initiate_txtSummary","Summary:","摘要:"}
                                                 ,{"frm_initiate_txtSearch","Search"," 查 找 "}
                                                 
                                                 ,{"frm_inbox_txt_delete_template_success","Note: Template delete successed!","注意: 模板删除成功!"}
                                                 ,{"frm_inbox_txt_delete_template_failed","Note: Template delete failed!","注意: 模板删除失败!"}

                                                 ,{"frm_initiate_gv_status","Status","状态"}
                                                 ,{"frm_initiate_gv_no","No","编号"}
                                                 ,{"frm_initiate_gv_process_name","Process Name","流程名称"}
                                                 ,{"frm_initiate_gv_summary","Summary","摘要"}
                                                 ,{"frm_initiate_gv_step_name","Step Name","步骤名称"}
                                                 ,{"frm_initiate_gv_process_version","Version ","版本 "}

                                                 ,{"frm_gv_list_txtPage","Page : ","页次 :&nbsp;&nbsp;"}
                                                 ,{"frm_gv_list_txtTotal","&nbsp;&nbsp;&nbsp;&nbsp;Total&nbsp;&nbsp;","&nbsp;&nbsp;&nbsp;&nbsp;共&nbsp;&nbsp;"}
                                                 ,{"frm_gv_list_txtRecords","&nbsp;&nbsp;records","&nbsp;&nbsp;条记录"}
                                                 ,{"frm_gv_list_txtFist","First","[首页]"}
                                                 ,{"frm_gv_list_txtForward","Forward","[前一页]"}
                                                 ,{"frm_gv_list_txtNext","Next","[下一页]"}
                                                 ,{"frm_gv_list_txtLast","Last","[尾页]"}    
                                                 ,{"frm_gv_list_txtGoTo","Go","转"}        

                                                 ,{"frm_inbox_title","Inbox","收件箱"}
                                                 ,{"frm_inbox_txtProcess","Process Name:","流程名:"}
                                                 ,{"frm_inbox_txtStep","Step Name:","步骤名称:"}
                                                 ,{"frm_inbox_txtSummary","Summary:","摘要:"} 
                                                 ,{"frm_inbox_txtIncidentFrom","Incident No:","序号:"}
                                                 ,{"frm_inbox_txtIncidentTo","To&nbsp;","&nbsp;至&nbsp;"}       
                                                 ,{"frm_inbox_btnSearch","Search"," 查询数据"}
                                                 ,{"frm_inbox_btnCancel","Cancel","取消实例"}

                                                 ,{"frm_inbox_assign_to","Assign &amp; Confer to:","指派或会办至:"}
                                                 ,{"frm_inbox_options","Options:","操作项:"}                                                 
                                                 ,{"frm_inbox_untile_date","Until date:","指派日期至:"}
                                                 ,{"frm_inbox_btn_assign_to","Assign to"," 指 派 "}
                                                 ,{"frm_inbox_btn_confer_to","Confer to"," 会 办 "}
                                                 ,{"frm_inbox_btn_take_bake_all_future_task","Take back All future tasks"," 收回所有将来指派任务 "}

                                                 ,{"frm_inbox_txt_assign_confer","Assign & Confer","指派或会办"}
                                                 ,{"frm_inbox_txt_take_back","Take back","任务收回"}
                                                 ,{"frm_inbox_txt_persoanl_info","Personal Info","个人信息"}
                                                 ,{"frm_inbox_txt_BatchApprove","Approve","批量审批"}
                                                 ,{"frm_inbox_img_BatchApprove","Process","批量处理"}
                                                 ,{"frm_inbox_personal_info_email","Email Address:","邮箱地址:"}
                                                 ,{"frm_inbox_personal_info_associate","Associate:","同事:"}
                                                 ,{"frm_inbox_personal_info_btn_add","Add","加入列表"}
                                                 ,{"frm_inbox_personal_info_btn_delete","Delete","移出列表"}
                                                 ,{"frm_inbox_personal_info_btn_save","Save","保 存"}
                                                 ,{"frm_inbox_txt_personal_info_success","Note: Success!","注意: 操作成功！"}
                                                 ,{"frm_inbox_txt_personal_info_failed","Note: Failed!","注意: 操作失败！"}

                                                 ,{"frm_inbox_txt_only_selected_tasks","Only selected tasks","仅限选择的项目"}
                                                 ,{"frm_inbox_txt_all_current_tasks","All current tasks","所有当前的任务"}
                                                 ,{"frm_inbox_txt_all_future_tasks","All future tasks","所有将来的任务"}
                                                 ,{"frm_inbox_txt_assign_confer_err","Note: You must choose a assigned user!","注意: 必须选择对应的被指派人！"}
                                                 ,{"frm_inbox_txt_assign_confer_success","Note: Task assign & confer to successed!","注意: 任务指派、会办成功！"}
                                                 ,{"frm_inbox_txt_assign_confer_failed","Note: Task assign & confer to failed!","注意: 任务指派、会办失败！"}

                                                 ,{"frm_inbox_txt_take_back_success","Note: Task take back successed!","注意: 任务收回成功！"}
                                                 ,{"frm_inbox_txt_take_back_failed","Note: Task take back failed!","注意: 任务收回失败！"}

                                                 ,{"frm_inbox_gv_monitor","Monitor","监控"}
                                                 ,{"frm_inbox_gv_status","Status","状态"}
                                                 ,{"frm_inbox_gv_process_name","Process Name","流程名称"}
                                                 ,{"frm_inbox_gv_summary","Summary","摘要"}
                                                 ,{"frm_inbox_gv_step_name","Step Name","步骤名称"}
                                                 ,{"frm_inbox_gv_start_time","Receive Time","接收时间"}
                                                 ,{"frm_inbox_gv_applicator","Applicator","申请人"}
                                                 ,{"frm_inbox_gv_owner","Owner","任务属主"}
                                                 ,{"frm_inbox_gv_incident_no","Inc No.","序号"}
                                                 ,{"frm_inbox_img_alt","click to monitor the incident graphic status!","单击监控实例状态！"}

                                                 ,{"frm_complete_title","Complete","已完成"}
                                                 ,{"frm_complete_txtProcess","Process Name:","流程名:"}
                                                 ,{"frm_complete_txtStep","Step Name:","步骤名称:"}
                                                 ,{"frm_complete_txtSummary","Summary:","摘要:"} 
                                                 ,{"frm_complete_txtIncidentFrom","Incident No:","序号:"}
                                                 ,{"frm_complete_txtIncidentTo","To","&nbsp;至&nbsp;"}       
                                                 ,{"frm_complete_btnSearch","Search"," 查 找 "}

                                                 ,{"frm_complete_gv_monitor","Monitor","监控"}
                                                 ,{"frm_complete_gv_status","Status","状态"}
                                                 ,{"frm_complete_gv_process_name","Process Name","流程名称"}
                                                 ,{"frm_complete_gv_summary","Summary","摘要"}
                                                 ,{"frm_complete_gv_step_name","Step Name","步骤名称"}
                                                 ,{"frm_complete_gv_start_time","Start Time","开始时间"}
                                                 ,{"frm_complete_gv_finish_time","Finish Time","完成时间"}
                                                 ,{"frm_complete_gv_applicator","Applicator","申请人"}
                                                 ,{"frm_complete_gv_owner","Owner","任务属主"}
                                                 ,{"frm_complete_gv_incident_no","Inc No.","序号"}
                                                 ,{"frm_complete_img_alt","click to monitor the incident graphic status!","单击监控实例状态！"}

                                                 ,{"frm_complete_grp_today","Date: Today","日期：今天"}
                                                 ,{"frm_complete_grp_yesterday","Date: Yesterday","日期：咋天"}
                                                 ,{"frm_complete_grp_week","Date: This Week","日期：本周"}
                                                 ,{"frm_complete_grp_last_week","Date: Last week","日期：上周"}
                                                 ,{"frm_complete_grp_2_week_ago","Date: 2 weeks ago","日期：两周以前"}
                                                 ,{"frm_complete_grp_earlier","Date: Earlier","日期：更早"}
                                                 ,{"frm_complete_grp_this_month","Date: This month","日期：本月"}
                                                 ,{"frm_complete_grp_last_month","Date: Last month","日期：上个月"}

                                                 ,{"frm_inbox_grp_can_tack_back","Note: Only can tack back","注意：允许收回的任务列表如下"}
                                                 ,{"frm_inbox_grp_can_cancel","Note: Only can cancel","注意：仅允许取消的实例如下"}

                                                 ,{"frm_monitor_title_list","Status List","状态列表"}
                                                 ,{"frm_monitor_title_graphic","Graphical View","状态监控"}
                                                 ,{"frm_monitor_close"," Close "," 关闭 "}
                                                 ,{"frm_monitor_gv_status","Status","状态"}
                                                 ,{"frm_monitor_gv_step_name","Step Name","步骤名称"}
                                                 ,{"frm_monitor_gv_owner","Owner","任务属主"}
                                                 ,{"frm_monitor_gv_client","Client","当前处理人"}
                                                 ,{"frm_monitor_gv_start_time","Receive Time","接收时间"}
                                                 ,{"frm_monitor_gv_end_time","Finish Name","完成时间"}   
                                                 ,{"frm_alt_open","Click to apply!","点击打开表单！"}
                                                 ,{"frm_alt_form","Click to open the form!","点击打开表单！"}
                                                 ,{"frm_alt_monitor","Click to monitor!","点击打开监控！"}
                                                };
        #endregion

        #region 构造函数
        public clsCommon()
        {

        }
        #endregion

        public DataTable GetDataTable(string ole, string sql)
        {
            clsDB.Storage(ole);
            return clsDB.Query(sql);
        }

        public string GetAccountFromDomain(string account)
        {
            DataTable dt_tmp = new DataTable();
            clsDB.Storage("bpmDB");
            dt_tmp = clsDB.Query("sp_ReturnAcc '" + account.Replace("'", "''") + "'");
            if (dt_tmp.Rows.Count > 0)
                return dt_tmp.Rows[0][0].ToString();
            else
                return account;
        }


        #region 是否已经登陆系统
        /// <summary>
        /// 是否已经登陆系统
        /// </summary>
        /// <returns></returns>
        public bool isLogin(string strName, string strAuthenticationType)
        {
            if (string.IsNullOrEmpty(comm_username))
            {
                if (strAuthenticationType.ToLower() == "negotiate")
                {
                    //chkLogin(strName.ToLower().Replace(@"\", @"/").Replace("apacdom", "apac.ad.ici.com").Replace("d20", "adcnda.d20.intra").Replace("d30", "d30.intra").Replace("d10", "d10.intra"));
                    return chkLogin(GetAccountFromDomain(strName.ToLower().Replace(@"\", @"/")));
                }

                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region 清空登陆信息
        /// <summary>
        /// 清空登陆信息
        /// </summary>
        /// <returns></returns>
        public void Logout()
        {
            comm_username = "";
            comm_userfullname = "";
            comm_userdepartment = "";
            comm_domain = "";
            clsRpt.Clear();
        }
        #endregion

        #region 根据ID取得对应的名称
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string getTextValue(string strId)
        {
            try
            {
                string strText = "";

                //数据合法性检查
                if (strId == null)
                {
                    strId = "";
                }

                //循环查找
                for (int i = 0; i < strTextType.Length; i++)
                {
                    if (strId == strTextType[i, 0])
                    {
                        //根据语言设置不同返回对应的名称
                        if (comm_language == "en-us")
                        {
                            strText = strTextType[i, 1];
                        }
                        else
                        {
                            strText = strTextType[i, 2];
                        }

                        break;
                    }
                }

                //返回值
                return strText;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion



        #region 根据用户名，取得并保存相关用户信息
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strUserName"></param>
        public bool chkLogin(string strUserName)
        {
            try
            {
                //如果验证通过的情况
                comm_domain = strUserName.Split('/')[0];
                comm_username = strUserName;
                comm_short_username = strUserName.Split('/')[1];

                Util.SetCookies("comm_username", comm_short_username, DateTime.MaxValue);
                Util.SetCookies("comm_domain", comm_domain, DateTime.MaxValue);

                //取得用户扩展信息
                OrgChart oc = new OrgChart();
                User ocUser = new User();
                UserPreferences up = new UserPreferences();
                oc.FindUser(comm_username, "", 0, out ocUser);

                //在当前用户存在的情况下
                if (ocUser != null)
                {
                    comm_userfullname = ocUser.strUserFullName; //用户名
                    comm_userdepartment = ocUser.strDepartmentName; //用户所属的部门     

                    try
                    {
                        ocUser.GetUserPrefs(out up);
                    }
                    catch (Exception)
                    {
                    }

                    comm_mail = up.strEmail;
                }
                else
                {
                    return false;
                }

                //析购函数
                ocUser = null;
                oc = null;

                #region 取得报表数据相关
                string str_department = "";
                string str_jobfunction = "";

                #region 部门取得
                //部门取得
                string strSQL = "";
                DataTable dt_tmp = new DataTable();
                strSQL = "select distinct name from departments where id in(select deptid from jobs where lower(name) = lower('" + comm_username + "'))";
                clsDB.Storage("bpmDB");
                dt_tmp = clsDB.Query(strSQL);

                //如果存在返回值的情况
                str_department = "";
                for (int i = 0; i < dt_tmp.Rows.Count; i++)
                {
                    if (i == dt_tmp.Rows.Count - 1)
                    {
                        str_department += dt_tmp.Rows[i]["name"].ToString().Trim();
                    }
                    else
                    {
                        str_department += dt_tmp.Rows[i]["name"].ToString().Trim() + "','";
                    }
                }
                #endregion

                #region 角色取得
                //角色取得
                strSQL = "select distinct name, jobfunction";
                strSQL += "  from (select rtrim(b.name) as name, rtrim(a.jobfunction) as jobfunction";
                strSQL += "          from (select deptid, jobfunction";
                strSQL += "                  from jobs";
                strSQL += "                 where id in (select supervisorid";
                strSQL += "                                from jobs a";
                strSQL += "                               where lower(a.name) = lower('" + comm_username + "')";
                strSQL += "                                 and jobtype = 64)) a,";
                strSQL += "               departments b";
                strSQL += "         where a.deptid = b.id";
                strSQL += "        union";
                strSQL += "        select rtrim(b.name) as name, rtrim(a.jobfunction) as jobfunction";
                strSQL += "          from jobs a, departments b";
                strSQL += "         where a.deptid = b.id";
                strSQL += "           and lower(a.name) = lower('" + comm_username + "')";
                strSQL += "           and jobtype <> 64) t_xxxx_tmp";

                clsDB.Storage("bpmDB");
                dt_tmp = clsDB.Query(strSQL);

                //如果存在返回值的情况
                str_jobfunction = "";
                for (int i = 0; i < dt_tmp.Rows.Count; i++)
                {
                    if (i == dt_tmp.Rows.Count - 1)
                    {
                        str_jobfunction += dt_tmp.Rows[i]["name"].ToString().Trim() + @"\" + dt_tmp.Rows[i]["jobfunction"].ToString().Trim();
                    }
                    else
                    {
                        str_jobfunction += dt_tmp.Rows[i]["name"].ToString().Trim() + @"\" + dt_tmp.Rows[i]["jobfunction"].ToString().Trim() + "','";
                    }

                }
                #endregion

                //设置报表参数相关
                clsRpt.set_rpt_para_value("{current_dept}", str_department);
                clsRpt.set_rpt_para_value("{current_job}", str_jobfunction);
                clsRpt.set_rpt_para_value("{current_user}", comm_username);
                clsRpt.set_rpt_para_value("{current_userfullname}", comm_userfullname);

                #region 判断是否为管理员
                strSQL = " select distinct a.grp_m_fk_grp_no";
                strSQL += "   from t_group_member a";
                strSQL += "  where grp_m_fk_grp_no='SYS-0001'";
                strSQL += "    and (a.grp_m_type_v in ('[current_dept]', '[all_dept]', '[current_user]','[all_user]', '[current_job]', '[all_job]')";
                strSQL += "     or (a.grp_m_type='1' and a.grp_m_type_v in ('" + clsRpt.get_rpt_para_value("{current_dept}") + "'))";
                strSQL += "     or (a.grp_m_type='2' and a.grp_m_type_v in ('" + clsRpt.get_rpt_para_value("{current_user}") + "'))";
                strSQL += "     or (a.grp_m_type='3' and a.grp_m_type_v in ('" + clsRpt.get_rpt_para_value("{current_job}") + "')))";

                clsDB.Storage("oleDB");
                dt_tmp = clsDB.Query(strSQL);
                if (dt_tmp.Rows.Count > 0)
                {
                    comm_is_administrator = true;
                }
                else
                {
                    comm_is_administrator = false;
                }
                #endregion

                #endregion

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion
    }
}
